package cn.lizemin.demo.thread.threadPool04;

import java.util.concurrent.*;

/**
 * @author: lizemin
 * @version: 1.0
 */
public class FutureDemo {
    //这是一个main方法,是程序的入口
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        //创建线程池对象
        ExecutorService es = Executors.newCachedThreadPool();
        //2.创建callable类型的任务对象
        Future<Integer> future = es.submit(new MyCall(2, 5));
//        test1(future);
        boolean cancel = future.cancel(true);
        System.out.println("取消任务执行的结果："+cancel);
        Integer integer = future.get(1, TimeUnit.SECONDS);
        System.out.println("任务执行的结果："+integer);

    }

    private static void test1(Future<Integer> future) throws InterruptedException, ExecutionException {
        //3.判断任务是否已经完成
        boolean done = future.isDone();
        System.out.println("第一次判断任务是否完成："+done);
        boolean cancelled = future.isCancelled();
        System.out.println("第一次判断任务是否取消："+cancelled);
        Integer value = future.get();
        System.out.println("任务执行的结果是："+value);

        boolean done2 = future.isDone();
        System.out.println("第二次判断任务是否完成："+done2);
        boolean cancelled2 = future.isCancelled();
        System.out.println("第二次判断任务是否取消："+cancelled2);
    }
}
class MyCall implements Callable<Integer>{
    private int a ; //
    private int b ; //

    public MyCall(int a, int b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public Integer call() throws Exception {
        String name = Thread.currentThread().getName();
        System.out.println(name+"准备开始计算....");
        //假设计算需要的时间为2s。
        Thread.sleep(2000);
        System.out.println(name+"计算完成....");
        return a + b;
    }

}
